package com.example.mydy;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.InviteLinkUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class InviteFriendsActivity extends AppCompatActivity {
    private TextView tvInviteCode;
    private TextView tvInviteLink;
    private Button btnCopyCode;
    private Button btnCopyLink;
    private Button btnShare;
    private TextView tvLevel1Count;
    private TextView tvLevel2Count;
    private TextView tvLevel3Count;
    private TextView tvTotalCount;
    private TextView tvTotalIncome;
    private TabLayout tabLayout;
    private ViewPager2 viewPager;
    private MockDataManager mockDataManager;
    private UserInfo currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_friends);

        // 设置标题栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("邀请好友");
        }

        // 初始化视图
        initViews();
        
        // 初始化数据
        mockDataManager = MockDataManager.getInstance();
        loadInviteData();
        setupTabLayout();
    }

    private void initViews() {
        tvInviteCode = findViewById(R.id.tv_invite_code);
        tvInviteLink = findViewById(R.id.tv_invite_link);
        btnCopyCode = findViewById(R.id.btn_copy_code);
        btnCopyLink = findViewById(R.id.btn_copy_link);
        btnShare = findViewById(R.id.btn_share);
        tvLevel1Count = findViewById(R.id.tv_level1_count);
        tvLevel2Count = findViewById(R.id.tv_level2_count);
        tvLevel3Count = findViewById(R.id.tv_level3_count);
        tvTotalCount = findViewById(R.id.tv_total_count);
        tvTotalIncome = findViewById(R.id.tv_total_income);
        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.view_pager);

        // 设置点击事件
        btnCopyCode.setOnClickListener(v -> copyToClipboard("邀请码", tvInviteCode.getText().toString()));
        btnCopyLink.setOnClickListener(v -> copyToClipboard("邀请链接", tvInviteLink.getText().toString()));
        btnShare.setOnClickListener(v -> shareInviteLink(tvInviteLink.getText().toString()));
    }

    private void loadInviteData() {
        String username = mockDataManager.getCurrentUsername();
        if (username == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 获取邀请码和链接
        String inviteCode = MockDataManager.getInviteCodeStatic(username);
        String inviteLink = InviteLinkUtils.generateInviteLink(username);
        tvInviteCode.setText(inviteCode);
        tvInviteLink.setText(inviteLink);

        // 设置下线统计信息
        Map<Integer, Integer> downlineCounts = MockDataManager.getDownlineUsersCount(username);
        if (downlineCounts != null) {
            tvLevel1Count.setText(String.valueOf(downlineCounts.getOrDefault(1, 0)));
            tvLevel2Count.setText(String.valueOf(downlineCounts.getOrDefault(2, 0)));
            tvLevel3Count.setText(String.valueOf(downlineCounts.getOrDefault(3, 0)));
            
            // 计算总人数
            int totalCount = downlineCounts.getOrDefault(1, 0) +
                           downlineCounts.getOrDefault(2, 0) +
                           downlineCounts.getOrDefault(3, 0);
            tvTotalCount.setText(String.valueOf(totalCount));
        } else {
            tvLevel1Count.setText("0");
            tvLevel2Count.setText("0");
            tvLevel3Count.setText("0");
            tvTotalCount.setText("0");
        }

        // 设置总收益
        double totalIncome = mockDataManager.getTotalDownlineIncome(username);
        tvTotalIncome.setText(String.format("¥%.2f", totalIncome));
    }

    private void setupTabLayout() {
        // 设置ViewPager2适配器
        DownlineUsersPagerAdapter adapter = new DownlineUsersPagerAdapter(this);
        viewPager.setAdapter(adapter);
        
        // 使用TabLayoutMediator将TabLayout与ViewPager2关联
        String[] titles = {"一级下线", "二级下线", "三级下线"};
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            tab.setText(titles[position]);
        }).attach();
    }

    private void copyToClipboard(String label, String text) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(this, label + "已复制到剪贴板", Toast.LENGTH_SHORT).show();
    }

    private void shareInviteLink(String inviteLink) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "邀请加入");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "快来加入我们吧！使用我的邀请链接注册: " + inviteLink);
        startActivity(Intent.createChooser(shareIntent, "分享邀请链接"));
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    // ViewPager2适配器
    private class DownlineUsersPagerAdapter extends FragmentStateAdapter {
        private final String[] titles = {"一级下线", "二级下线", "三级下线"};

        public DownlineUsersPagerAdapter(AppCompatActivity activity) {
            super(activity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return DownlineUsersFragment.newInstance(position + 1);
        }

        @Override
        public int getItemCount() {
            return titles.length;
        }
    }

    public static class DownlineUsersFragment extends Fragment {
        private static final String ARG_LEVEL = "level";
        private int level;
        private RecyclerView recyclerView;
        private LinearLayout emptyView;
        private DownlineUserAdapter adapter;

        public static DownlineUsersFragment newInstance(int level) {
            DownlineUsersFragment fragment = new DownlineUsersFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_LEVEL, level);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                level = getArguments().getInt(ARG_LEVEL);
            }
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_downline_users, container, false);
            recyclerView = view.findViewById(R.id.recycler_view);
            emptyView = view.findViewById(R.id.empty_view);
            
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            
            loadDownlineUsers();
            
            return view;
        }

        private void loadDownlineUsers() {
            // 获取当前用户名
            String username = MockDataManager.getInstance().getCurrentUsername();
            
            if (username != null) {
                // 获取指定级别的下线用户详情
                Map<String, Double> downlineUsers = MockDataManager.getDownlineUsersDetail(username, level);
                
                if (downlineUsers.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                } else {
                    recyclerView.setVisibility(View.VISIBLE);
                    emptyView.setVisibility(View.GONE);
                    
                    // 转换为用户列表
                    List<String> usernames = new ArrayList<>(downlineUsers.keySet());
                    adapter = new DownlineUserAdapter(usernames, downlineUsers);
                    recyclerView.setAdapter(adapter);
                }
            }
        }

        private class DownlineUserAdapter extends RecyclerView.Adapter<DownlineUserAdapter.ViewHolder> {
            private List<String> usernames;
            private Map<String, Double> contributions;

            public DownlineUserAdapter(List<String> usernames, Map<String, Double> contributions) {
                this.usernames = usernames;
                this.contributions = contributions;
            }

            @NonNull
            @Override
            public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_downline_user, parent, false);
                return new ViewHolder(view);
            }

            @Override
            public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
                String username = usernames.get(position);
                UserInfo userData = MockDataManager.findUserByUsername(username);
                
                if (userData != null) {
                    holder.tvUsername.setText(userData.getNickname() != null ? userData.getNickname() : username);
                    
                    // 显示贡献值
                    double contribution = contributions.get(username);
                    holder.tvContribution.setText(String.format("贡献: ¥%.2f", contribution));
                    
                    // 加载头像
                    String avatarUrl = MockDataManager.getInstance().getUserAvatarUrl(username);
                    if (avatarUrl != null && !avatarUrl.isEmpty()) {
                        Picasso.get().load(avatarUrl).placeholder(R.drawable.ic_avatar_placeholder).into(holder.ivAvatar);
                    } else {
                        holder.ivAvatar.setImageResource(R.drawable.ic_avatar_placeholder);
                    }
                } else {
                    holder.tvUsername.setText(username);
                    holder.tvContribution.setText("贡献: ¥0.00");
                    holder.ivAvatar.setImageResource(R.drawable.ic_avatar_placeholder);
                }
            }

            @Override
            public int getItemCount() {
                return usernames.size();
            }

            public class ViewHolder extends RecyclerView.ViewHolder {
                ImageView ivAvatar;
                TextView tvUsername;
                TextView tvContribution;

                public ViewHolder(@NonNull View itemView) {
                    super(itemView);
                    ivAvatar = itemView.findViewById(R.id.iv_avatar);
                    tvUsername = itemView.findViewById(R.id.tv_username);
                    tvContribution = itemView.findViewById(R.id.tv_contribution);
                }
            }
        }
    }
} 